<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------
namespace app\property\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;
use think\facade\Config;
use app\wechat\controller\WechatTool;
use think\facade\Env;
use think\facade\App;
/**工具**/
use PHPExcel;//tp5.1用法
use PHPExcel_IOFactory;

use wxpay\database\WxPayResults;
use wxpay\database\WxPayUnifiedOrder;
use wxpay\NativePay;
use wxpay\WxPayApi;
use wxpay\WxPayConfig;
use wxpay\Phpqrcode;

use think\facade\Log;
/**
 * 物业管理
 * Class User
 * @package app\worker\controller
 */
class Company extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    // protected $table = 'CompanyUser';
    protected $table = 'company';
    protected $table_department = 'SystemMenu';
    protected $view_table = 'view_company';
    /**
     * 租户管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {

        $this->title = '租户管理';
        $dbconf = $this->getconfig('vister_db');
        $where ='';
        $uinfo = $this->getGuserinfo();

        switch ($uinfo['db1']['authorize']) {
            case 1:
                # code...
                break;
            case 8:
                $company_res =  Db::connect($dbconf)->table('view_company')->field('id')->where(['property_id' => $uinfo['db2']['companyid']])->order('createtime desc')->select();

                if($company_res){
                    $inid = array_column($company_res, 'id');
                    $inid = implode(",", $inid);
                    $where = 'id in ('.$inid.')';
                }else{
                     $where = 'id  = 0';
                }
               
                # code...
                break;
            default:
                # code...
                break;
        }
// var_dump($uinfo);
         $create_at_first=trim($this->request->param('create_at_first'))?strtotime($this->request->param('create_at_first')):'';
         $create_at_last=trim($this->request->param('create_at_last'))?strtotime($this->request->param('create_at_last'))+3600*24:'';
                    
                     if(!$create_at_first||!$create_at_last){

                          $this->_query(Db::connect($dbconf)->table($this->view_table))->where($where)->where('type = 1')->like('name,code,corporation')->equal('status')->where('deleteTime is null')->order('createtime desc')->page();

                        }
                        else{
                          $this->_query(Db::connect($dbconf)->table($this->view_table))->where($where)
                                                                                        ->where('type = 1')
                                                                                        ->like('name,code,corporation')
                                                                                        ->equal('status')
                                                                                        ->where('deleteTime is null')
                                                                                        ->where('createtime','between',[$create_at_first,$create_at_last])
                                                                                        ->order('createtime desc')
                                                                                        ->page();
                    }
            
    }
    /**
     * 同步公司(弃用)
     * @auth        true
     * @throws      \think\Exception
     * @throws      \think\exception\PDOException
     * @Author      GNLEON
     * @HttpRequest                                              get|post
     * @Param                                     -
     * @DateTime    2020-09-11
     * @LastTime                                  2020-09-11
     * @copyright   [copyright]
     * @license     [license]
     * @return      [type]                        [description]
     */
    public function sync(){
        return;
        $dbconf = $this->getconfig('vister_db');
        $res = Db::connect($dbconf)->table('view_company')->select();
        $countinsert = 0;

        foreach ($res as $key => $value) {
            # code...
            $check = Db::table('company')->where('code',$value['code'])->find();
            if($check==NULL){
                $data = [
                    'id' => $value['id'],
                    'name' => $value['name'],
                    'code' => $value['code'],
                    'corporation' => $value['corporation'],
                    'address' => $value['address'],
                    'imgurl' => $value['imgurl'],
                    'score' => $value['score'],
                    'expiretime' => $value['expiretime'],
                    'createuid' => $value['createuid'],
                    'createtime' => $value['createtime'],
                    'status' => $value['status'],
                ];
                // if($value['name']!=NULL){
                $result = Db::name('company')->insert($data);
                $countinsert++;
                echo '<div style="text-align: center;">成功同步-'.$value['name'].'</div></br>';
                // }

            }else{
                /*update*/
            }

        }

        echo '<div style="text-align: center;">同步完成--一共同步:'.$countinsert.'家企业</div>';


    }
    /**
     * 获取公司列表
     */
    public function getlist(){
        $dbconf = $this->getconfig('vister_db');
        $res = Db::connect($dbconf)->table('view_company')->select();
        return toJson(['code'=>200,'data'=>$res]);

    }
    /**/
    public function getappuserlist(){
        $companyid = $this->request->param('companyid');
        if(empty($companyid)){return toJson(['code'=>400]);}
        $dbconf = $this->getconfig('vister_db');
        $where = 'Interviewees = 1 and companyid = '.$companyid;
        $res = Db::connect($dbconf)->table('view_user')->where($where)->select();
        return toJson(['code'=>200,'data'=>$res]);
    }
    public function getdeptlist(){
        $deptid =  $this->request->param('deptid');
        $companyid = $this->request->param('companyid');
        $dbconf = $this->getconfig('vister_db');
        $where =  'companyid = '.$companyid;
        $res = Db::connect($dbconf)->table('dept')->where($where)->select();
        return toJson(['code'=>200,'data'=>$res]);
    }
    public function index_search()
    {
         // $this->_query($this->table)->like('nickname,svn_username,department')->equal('status')->page();
        // $list=Db::name('CompanyUserDepartment')->order('id')->select();
        //   $this->assign('list',$list);
        //   return $this->fetch();
    }
    /**
     * 添加租户(公司)
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        $dbconf = $this->getconfig('vister_db');
        
        $userinfo = $this->getGuserinfo();

        $ulist = Db::connect($dbconf)->table('view_user')->select();
        $this->assign('data',['userlist'=>$ulist]);
        if($this->request->isPost()){
            $companyname = $this->request->param('companyname');
            $createuid = $this->request->param('createuid');
            $corporation = $this->request->param('corporation');
            $address = $this->request->param('address');
            $mobile = $this->request->param('mobile');
            $code = $this->request->param('code')?:NULL;
            $upye_switch = $this->request->param('upye_switch')=='on'?'on':'off';
            $createuid = $this->request->param('createuid')?:0;

            $data = [
                'name' => $companyname,
                'corporation' => $corporation,
                'address' => $address,
                'createtime' => time(),
                'status' => 2,
                'examinetime' => time(),
                'type' => 1,
                'mobile' => $mobile,
                'code' => $code,
                'createuid' => $createuid,
            ];

            if($upye_switch=='on'){
              $data['imgurl'] = $this->request->param('local_url');
            }
            $check = Db::connect($dbconf)->table($this->view_table)->where('corporation like "%'.$data['corporation'].'%"')->find();
            if($check){$this->error('公司已存在');}

            $res_companyid = Db::connect($dbconf)->table($this->table)->insertGetId($data);

            /**公司关系**/
             $data = [
                'property_id' => $userinfo['db2']['companyid'],
                'incompany_id' => $res_companyid,
                'createtime' => time(),
            ];
            if($userinfo['db1']['authorize']==1){$data['property_id']=1;}
              $check = Db::connect($dbconf)->table('view_property_relation')->where('incompany_id = '.$res_companyid)->find();
            if($check){
              $res = Db::connect($dbconf)->table('property_relation')->where('id = '.$check['id'])->data(['property_id' => $data['property_id']])->update();
            }else{
              $res = Db::connect($dbconf)->table('property_relation')->insert($data);
            }

            $this->success('添加租户成功.');
        }
        $this->_form(Db::connect($dbconf)->table($this->table), 'form');
    }

    /**
     * 批量导出|入租户
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-13T09:23:53+0800
     * @LastTime     2020-10-13T09:23:53+0800
     * @return       [type]                       [description]
     * @remark  PhpSpreadsheet请替换为
     */
    public function export(){
        $userinfo = $this->getGuserinfo();
        $dbconf = $this->getconfig('vister_db');

        switch ($userinfo['db1']['authorize']) {
            case '1':
                $property_id = 0;
                # code...
                break;
            case '8':
                $property_id = $userinfo['db1']['companyid'];
                # code...
                break;
            default:
                $this->error('无权限操作');
                # code...
                break;
        }
        
        $excel = $this->request->file('excel');
        /****/
        if($this->request->param('export') == 'out'){
            $objPhpExcel = new \PHPExcel();

            $create_at_first = $this->request->param('create_at_first');
            $create_at_last = $this->request->param('create_at_last');
            $limit = $this->request->param('limit')?:110;
            $page = $this->request->param('page')?:0;

            $name = $this->request->param('name')?:"";
            $search[0] = $name?'name like "%'.$name.'%"':"";

            $code = $this->request->param('code')?:"";
            $search[1] = $code?'code like "%'.$code.'%"':"";

            $corporation = $this->request->param('corporation')?:"";
            $search[2] = $corporation?'corporation like "%'.$corporation.'%"':"";

            $status = $this->request->param('status')?:"";
            $search[3] = $status?'status = '.$status:"";
            //
            if($userinfo['db1']['authorize'] == '8'){
                $search[4] = 'property_id = '.$userinfo['db2']['companyid']; 
            }

            $where = '';
    
            foreach ($search as $key => $value) {
                # code...
                if($value){
                    $where=$where.$value.' and ';
                }
            }
            $where=substr($where,0,strlen($where)-5);

            if($create_at_first && $create_at_last){
                $res_data = Db::connect($dbconf)->table($this->view_table)->field('id,name,code,corporation,user_name,address,imgurl,status,mobile,property_name,type')
                                                                          ->where($where)
                                                                           // ->where('type = 1')
                                                                           //->equal('status')
                                                                           ->where('createtime','between',[$create_at_first,$create_at_last])
                                                                           ->limit($page,$limit)
                                                                           ->select();

            }else{
                $res_data = Db::connect($dbconf)->table($this->view_table)->field('id,name,code,corporation,user_name,address,imgurl,status,mobile,property_name,type')
                                                                          ->where($where)
                                                                           // ->where('type = 1')
                                                                           //->equal('status')
                                                                           ->limit($page,$limit)
                                                                           ->select();
            }
            /*
             设置表头标题
            */
            $rowVal = [
                    '编号',
                    '租户公司名称',
                    '租户公司信用代码',
                    '租户公司法定代表人',
                    '租户公司负责人',
                    '租户公司地址',
                    '租户公司营业执照',
                    '租户公司审核状态',
                    '租户公司联系电话',
                    '租户物业管理公司名称',
                    '租户类型',
            ];
            //设置表头的样式
            foreach ($rowVal as $k=>$r){
                $objPhpExcel
                    ->getActiveSheet()
                    ->getStyleByColumnAndRow($k,1)
                    ->getFont()->setBold(true);//字体加粗
                $objPhpExcel
                    ->getActiveSheet()
                    ->getStyleByColumnAndRow($k,1)
                    ->getAlignment()
                    ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//文字居中
                $objPhpExcel
                    ->getActiveSheet()
                    ->setCellValueByColumnAndRow($k,1,$r);

            }
            //设置当前的sheet索引 用于后续内容操作
            $objPhpExcel->setActiveSheetIndex(0);
            $objActSheet = $objPhpExcel->getActiveSheet();

            $title="租户数据表";//
            $objActSheet->setTitle($title);
                $styleArray = array(
                    'font' => array(
                        'color' => array('rgb' => '000000'),
                        'size' => 12,
                        'name' => 'Verdana'
                    ));
            foreach ($res_data as $index => $item) {
                # code...
                // $num=$index+2;

                    $line = $index+2;
                    $col = 0;
                foreach ($item as $key => $value) {
                    # code...
                    #设置内容
                        if($key == 'status'){

                            switch ($value) {
                                case '0':
                                    # code...
                                    $value = '未审核';
                                    break;
                                case '1':
                                    $value = '未通过';
                                    # code...
                                    break;
                                case '2':
                                    $value = '已通过';
                                    break;
                                default:
                                    # code...
                                    $value = '未知';
                                    break;
                            }
                        }
                        if($key == 'type'){
                            
                            switch ($value) {
                                case '1':
                                    # code...
                                    $value = '租户公司';
                                    break;
                                case '2':
                                    # code...
                                    $value = '物业公司';
                                    break;
                                case '3':
                                    # code...
                                    $value = '普通公司';
                                    break;
                                default:
                                    # code..
                                    $value = '未知';
                                    break;
                            }

                        }
                        $objActSheet->setCellValueByColumnAndRow($col, $line, $value);
                        $objActSheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode('@');
                        $objActSheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);
                        $col++;
                }

            }

           $name=date('Y-m-d-H-i');//设置文件名

           header("Content-Type: application/force-download");
           header("Content-Type: application/octet-stream");
           header("Content-Type: application/download");
           header("Content-Transfer-Encoding:utf-8");
           header("Pragma: no-cache");
           header('Content-Type: application/vnd.ms-excel');
           header('Content-Disposition: attachment;filename="'.$title.'_'.urlencode($name).'.xls"');
           header('Cache-Control: max-age=0');
           $objWriter = \PHPExcel_IOFactory::createWriter($objPhpExcel, 'Excel5');
           $objWriter->save('php://output');

        }
        //end out
       
        //excel in
        if(!$excel){$this->fetch('');}
        //文件保存路径
        $rootPath = Env::get('root_path');
        $filepath = $rootPath."public/excel";
 
        $info = $excel->validate(['size' => 1024 * 1024 * 80, 'ext' => 'xls,xlsx'])->move($filepath,false);

        $fileName = $filepath . '/' . $info->getSaveName();

        $phpExcelObj = \PHPExcel_IOFactory::load($fileName);
        $sheet = array();
        $sheet[] = $phpExcelObj->getSheet(0)->toArray();
        
        $name = '';
        //dump($sheet[0]);
        //把表格数据遍历为数组
        if ($info) {
        $repcae_company = [];
        foreach($sheet[0] as $key=>$value){

            if($key!=0){
                foreach($value as $k=>$val){

                    if($k == 0){
                        $indata['name'] = $val;
                    }
                    if($k == 1){
                        $indata['corporation'] = $val;
                    }
                    if($k == 2){
                        $indata['mobile'] = $val;
                    }
                    if($k == 3){
                        $indata['address'] = $val;
                    }

                }
                $indata['createtime'] = time();
                $indata['status'] = 2;
                $indata['examinetime'] = time();
                $indata['type'] = 1;
                try{
                     $check = Db::connect($dbconf)->table($this->view_table)->where('name like "'.$indata['name'].'"')->find();
                     if($check){
                        array_push($repcae_company, $indata['name']);
                        Log::info('企业重复-'.date('Y-m-d H:i:s',time()).json_encode($indata,JSON_UNESCAPED_UNICODE));
                     }else{
                        $recompanyid = Db::connect($dbconf)->table($this->table)->insertGetId($indata);
                     }
                     //插入关系
                     if($recompanyid){
                        $data = [
                            'property_id' => $property_id,
                            'incompany_id' => $recompanyid,
                            'createtime' => time(),
                        ];
                        $res = Db::connect($dbconf)->table('property_relation')->insert($data);
                     }
                     
                }catch(\Throwable $th){
                    Log::info('添加企业失败-'.date('Y-m-d H:i:s',time()).json_encode($indata));
                }
                
                
            }
            
        }

        // $this->view->assign('class',$class);
        // $this->view->assign('batch',$batch);
        // $this->view->assign('subject',$subject);
        // return $this->view->fetch();

    }else{
        // 上传失败获取错误信息
        //echo $file->getError();
        // return ['status'=>0,'msg'=>'上传失败'];
        // return $file->getError();
        $this->error('导入失败,请稍后再试');
    }   
        if(count($repcae_company)>0){

            $tips_company = implode(",<br>",$repcae_company);
            $this->success('导入成功,以下企业已存在,无需添加。<br>'.$tips_company);
        }
        $this->success('导入成功.');
    }


    /**
     * 修改租户信息
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {

        // array(11) { ["id"]=> string(2) "22" ["spm"]=> string(13) "m-209-210-211" ["open_type"]=> string(5) "modal" ["companyname"]=> string(42) "广州联汇智能电子科技有限公司" ["code"]=> string(18) "91440101MAFEOEAME2" ["user_name"]=> string(3) "123" ["corporation"]=> string(9) "向树春" ["mobile"]=> string(11) "15632323232" ["address"]=> string(69) "广州市天河区珠村北环路50号1栋310A(不可作厂房使用>" ["upye_switch"]=> string(2) "on" ["local_url"]=> string(64) "http://pc.zsicp.com/upload/716953771a0c6f09/14c44f68fc502bdd.jpg" }
        // 
        // array(11) { ["id"]=> string(2) "24" ["spm"]=> string(13) "m-209-210-211" ["open_type"]=> string(5) "modal" ["companyname"]=> string(39) "四川渝懒人餐饮管理有限公司" ["code"]=> string(18) "91510104MA6CNGX91E" ["user_name"]=> string(6) "123123" ["corporation"]=> string(9) "唐仕德" ["mobile"]=> string(11) "14785236985" ["address"]=> string(46) "都市徽酒因七界三段路练单元子楼0" ["upye_switch"]=> string(2) "on" ["local_url"]=> string(0) "" }
        $userinfo = $this->getGuserinfo();
        $dbconf = $this->getconfig('vister_db');
        $ulist = Db::connect($dbconf)->table('view_user')->select();
        $id = $this->request->param('id');
        if(!$id){$this->error("参数错误");}
        $member_info = Db::connect($dbconf)->table('view_store_member')->where('companyid = '.$id)->find();

        //var_dump($userlist);

        if($this->request->isPost('')){
            $upye_switch = $this->request->param('upye_switch')=='on'?'on':'off';
            switch ($userinfo['db1']['authorize']) {
                case '1':
                    $this->error('管理员请从公司管理操作');
                    # code...
                    break;
                case '8':
                    $id = $this->request->param('id');
                    $createuid = $this->request->param('createuid');
                    $checkuinfo = Db::connect($dbconf)->table('view_user')->where('id = '.$createuid)->find();
                    if($checkuinfo['companyid']!=NULL && $checkuinfo['companyid']!=$id){$this->error('该用户已是其他公司员工');}
                    $phone = $this->request->param('mobile');
                    $code = $this->request->param('code');
                    $data =  [
                        'createuid' => $createuid,
                        'mobile' => $phone,
                    ];
                    if($upye_switch=='on'){
                        $check = Db::connect($dbconf)->table($this->view_table)->where('code like "%'.$code.'%"')->find();
                        if($check){$this->error('公司已存在');}

                        $data['name'] = $this->request->param('companyname');
                        $data['code'] = $code;
                        $data['address'] = $this->request->param('address');
                        $data['corporation'] = $this->request->param('corporation');
                        $data['imgurl'] = $this->request->param('local_url');

                    }
                    # code...
                    break;
                default:
                    # code...
                    break;
            }
                $res = Db::connect($dbconf)->table($this->table)->where(['id' => $id])->data($data)->update();
                $this->success('更新租户信息成功');
        }
        $this->assign('data',[
          'userlist'=>$ulist,
          'member_info' => $member_info,
        ]);
        $this->_form(Db::connect($dbconf)->table($this->view_table), 'form');    
    }
    /**
     * 租户详情
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-13T09:03:10+0800
     * @LastTime     2020-10-13T09:03:10+0800
     * @return       [type]                       [description]
     */
    public function details(){
        //var_dump($this->request->param(''));

         $dbconf = $this->getconfig('vister_db');
         $this->_form(Db::connect($dbconf)->table($this->view_table), '');   
    }

    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        if ($this->request->isGet()) {
            $where = ['status' => '1', 'is_deleted' => '0'];
            $this->auths = Db::name('company_user_auth')->where($where)->order('sort desc,id desc')->select();
            array_unshift($this->auths, ['id' => '0', 'title' => '所有权限', 'path' => '/']);
            $data['svn_authorize'] = isset($data['svn_authorize']) ? explode(',', $data['svn_authorize']) : [];
        } else {
            if (isset($data['svn_authorize']) && is_array($data['svn_authorize'])) {
                $data['svn_authorize'] = join(',', $data['svn_authorize']);
            } else {
                $data['svn_authorize'] = '';
            }
            // $macs = [];
            // foreach (explode(PHP_EOL, preg_replace("/\s+/", PHP_EOL, trim($data['mobile_macs']))) as $mac) {
            //     if (DataService::applyMacValue($mac)) $macs[] = $mac;
            // }
            // $data['mobile_macs'] = join(PHP_EOL, array_unique($macs));
        }
    }

    /**
     * 更改租户状态
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
     public function state()
    {

        $status = $this->request->param('status');
        $code = $this->request->param('code');
        if($status == 2){
            $where = 'code = "'.$code.'"';
            /*此处用户id对应到　dev数据库---以下操作仅对dev操作*/
            // $companydata = Db::table('company')->where($where)->find();
            $dbconf = $this->getconfig('vister_db');
            $companydata = Db::connect($dbconf)->table('view_company')->where($where)->find();
            if(!$companydata){$this->error('公司信息错误.');}
            $data = [
                'companyid' => $companydata['id'],
                'roleid' =>2,
                'Interviewees' => 1
            ];
            $where = 'id = '.$companydata['createuid'];
            $res = Db::connect($dbconf)->table('user')->where($where)->data($data)->update();
            $where = 'code = "'.$code.'"';
            $data = [
                'status' => 2,
                'examinetime' => time(),
            ];
            $res = Db::connect($dbconf)->table('company')->where($where)->data($data)->update();

            $data = [
                'openid' => $companydata['openid'],
                'url' => 'https://devs.zsicp.com/h5/',
                'title' => '审核营业执照',
                'name' => $companydata['user_name'],
                'mobile' => $companydata['mobile'],
                'time' => date("Y-m-d H:i:s",time()),
                'status' => '审核通过',
                'remark' => '',
            ];
            $sendRes = WechatTool::send_message($data);


            /*自动新增部门*/
            $where = 'companyid = '.$companydata['id'];
            $countdept =  Db::connect($dbconf)->table('dept')->where($where)->count();
            if($countdept==0){
                $deptarr = ['技术部','保安部','行政部'];
                $indeptdata = [
                    'companyid' =>$companydata['id'],
                    'createtime' =>time(),
                ];
                for ($i=0; $i <3 ; $i++) { 
                    # code...
                    if($i==1){
                        $indeptdata['name'] =$deptarr[$i];
                        $indeptdata['is_security'];
                    }else{
                        $indeptdata['name']=$deptarr[$i];
                    }
                    Db::connect($dbconf)->table('dept')->insert($indeptdata);
                }
            }
          if($res){$this->success('审核成功');}
          $this->error('审核失败');
        }
    }
    /**
     * 删除租户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $dbconf = $this->getconfig('vister_db');
        $userinfo = $this->getGuserinfo();
        if($this->request->isPost()){      
        $id=trim($this->request->param('id'));
        // dump($id);
        //物业管理下删除租户
        switch ($userinfo['db1']['authorize']) {
            case '1':
                $this->error('超级管理员请从公司管理进行操作');
                # code...
                break;
            case '8':
                try{

                    Db::connect($dbconf)->table('property_relation')->where("incompany_id in ($id) AND property_id = ".$userinfo['db2']['companyid'])->data(['property_id'=>0])->update();

                }catch (\Throwable $th){

                }
                $this->success('删除租户成功');
                break;
            default:
                $this->error('无操作权限');
                # code...
                break;
        }
        $data = Db::connect($dbconf)->table($this->table)->where("id in ($id)")->useSoftDelete('deleteTime',time())->delete();
        if($data){
            $this->success('删除租户成功');
        }
        }
    }
    /**
     * 发送微信模板消息
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-09-11T15:29:10+0800
     * @LastTime     2020-09-11T15:29:10+0800
     * @return       [type]                       [description]
     */
    public function sendwx(){
        $dbconf = $this->getconfig('vister_db');
        $userinfo = $this->getGuserinfo();

        $tpl = $this->request->param('wxtpl');
        $message  = $this->request->param('wxmessag');
        $company_id = $this->request->param('id');
        $type = $this->request->param('type');//sendall

        switch ($tpl) {
          //收费做成定时 批量发送 以下需要保留手动发送
            case '1':
            //string(96) "{{first.DATA}}
            // 缴费金额：{{keyword1.DATA}}
            // 缴费时间：{{keyword2.DATA}}
            // {{remark.DATA}}"
            // array(7) { ["id"]=> string(2) "26" ["spm"]=> string(13) "m-209-210-211" ["open_type"]=> string(5) "modal" ["wxtpl"]=> string(1) "1" ["commodity_list"]=> string(2) "15" ["price"]=> string(8) "99999.00" ["wxmessag"]=> string(4) "2222" }

                // {{first.DATA}}
                // 客户需求：{{keyword1.DATA}}
                // 客户名称：{{keyword2.DATA}}
                // 提出时间：{{keyword3.DATA}}
                // {{remark.DATA}}
                $product_id = $this->request->param('commodity_list');
                $product_id = 15;
                $price = $this->request->param('price');

                //$send_uinfo = Db::connect($dbconf)->table('view_user')->where('roleid = 2 and companyid in ('.$company_id.')')->select();
                $send_uinfo = Db::connect($dbconf)->table('view_company')->where('id in ('.$company_id.')')->select();

                foreach ($send_uinfo as $key => $companyinfo_key) {
                  $company_data = Db::connect($dbconf)->table('view_company')->where('id = '.$companyinfo_key['id'])->find();
                  if(!$company_data){continue;}
                  $commodity_type = 'TEST';
                  $out_trade_no = makeOrdersn('HL'.$commodity_type);
                  $indata = [
                    'userid' => $companyinfo_key['createuid'],
                    'commodityId' => $product_id,
                    'openid' => $companyinfo_key['openid'],
                    'payType' => 1,
                    'status' => 1,
                    'amount' => 1,
                    'price' => $price/100,
                    'createtime' => time(),
                    'tradeNo' => $out_trade_no,
                    'remark' => '后台订单-物业收费-',
                  ];

                  $res = Db::connect($dbconf)->table('commodity_orders')->insert($indata);
    
                  $data = [
                           'template_id' => '_Om5X-F675FlAPf5ceRRjA95SXWbpL0KGLDWR1Hzd_I',
                           'array' => [
                               'first' => "(订阅通知:)你好,{$company_data["name"]} -".date("Y年m月",time())."缴费账单已生成",
                               'keyword1' => $this->request->param('price'),
                               'keyword2' => date("Y-m-d",time()+3600*24*2).'之前请您及时缴费',
                               'remark' => $message
                              ],
            
                  ];
                  $url = 'http://pc.zsicp.com/personal/pay/mobilepay?scode='.$out_trade_no;

                  try{
                      $sendRes = WechatTool::send_WXtpl($companyinfo_key['openid'],$data,$url);
                  }catch(\Throwable $th){
                      Log::info("发送微信消息失败".time()."-".$out_trade_no);
                  }
                  
                }
                // $price = curmoney($price);
                // $product_info = Db::connect($dbconf)->table('commodity')->where('id = '.$product_id)->find();
                // if($product_info['year']!=0){
                //     $commodity_type = 'Y';
                // }elseif ($product_info['month']!=0) {
                //      $commodity_type = 'M';
                //     # code...
                // }elseif ($product_info['day']!=0) {
                //      $commodity_type = 'D';
                //     # code...
                // }else{
                //     $this->error('商品信息不存在或已删除');
                // }

                
                // //TODO 进行业务处理
                // //TODO 生成二维码
                // $notify = new NativePay();
                // $input = new WxPayUnifiedOrder();
                // $input->setBody("套餐充值");
                // $input->setAttach("xxx");
                // $input->setOutTradeNo($out_trade_no);
                // $input->setTotalFee($price);//以分为单位
                // $input->setTimeStart(date("YmdHis"));
                // $input->setTimeExpire(date("YmdHis", time() + 10));
                // $input->setGoodsTag("");
        
                // $input->setNotifyUrl('http://pc.zsicp.com/personal/pay/notify');
                // $input->setTradeType("JSAPI");
                // //$product_id 为商品自定义id 可用作订单ID
                // $input->setProductId($product_id);
                // $input->setOpenid($send_uinfo['openid']);
                // $result = $notify->getPayUrl($input);

                // $result = WxPayApi::unifiedOrder($input);
                
                  /**
                   * 生成订单
                   */
                 
                    # code...

                # code...
                break;
            case '2':
                //$send_uinfo = Db::connect($dbconf)->table('view_user')->where('roleid = 2 and companyid in ('.$company_id.')')->select();
                $send_uinfo = Db::connect($dbconf)->table('view_company')->where('id in ('.$company_id.')')->select();
                //var_dump($send_uinfo);
                foreach ($send_uinfo as $key => $companyinfo_key) {
                  $company_data = Db::connect($dbconf)->table('view_company')->where('id = '.$companyinfo_key['id'])->find();
                  if(!$company_data){continue;}
                  $data = [
                           'template_id' => 'Exkadv3HIt-2WQtMdfi3hFMwZmLl1eTZRXNj8SV4bwI',
                           'array' => [
                               'first' => "订阅下达通知",
                               'keyword1' => "阅读消息",
                               'keyword2' => "{$company_data['name']}",
                               'keyword3' => date("Y年m月d日 H:i:s",time()),
                               'remark' => $message,
                           ],
              
                  ];
                  $url = '';

                  # code...
                  try{
                      $sendRes = WechatTool::send_WXtpl($companyinfo_key['openid'],$data,$url);
                  }catch(\Throwable $th){
                      Log::info("发送微信消息失败".time()."-".$companyinfo_key['openid']);
                  }
                }

                # code...
                break;
            default:
                $data = [];
                # code...
                break;
        }

        if($this->request->isPost()){
          $this->success('发送成功');
        }
        
        //$this->fetch('sendwx', $vars = [], $node = null);
        //物业套餐
        switch ($userinfo['db1']['authorize']) {
          case '1':
            $where = '';
            # code...
            break;
          case '8':
            $where = 'userid = '.$userinfo['db2']['id'];
            break;
          default:
            $this->error('无权限操作');
            # code...
            break;
        }
        $commodity_list = Db::connect($dbconf)->table('commodity')->where($where)->select();
        //$assigndata['commodity_list'] = $commodity_list
        $this->assign('commodity_list',$commodity_list);
        if($type=='sendall'){
          $this->assign('plsend',true);
          $this->assign('plsend_id',$company_id);
        }else{
          $this->assign('plsend',false);
        }
        $this->_form(Db::connect($dbconf)->table($this->table), 'sendwx');
    }
    /**
     * 下载excel模板
     * @auth        true
     * @throws      \think\Exception
     * @throws      \think\exception\PDOException
     * @Author      GNLEON
     * @HttpRequest                                              get|post
     * @Param                                     -
     * @DateTime    2020-10-14
     * @LastTime                                  2020-10-14
     * @copyright   [copyright]
     * @license     [license]
     * @return      [type]                        [description]
     */
    public function down(){

        $file_dir =  Env::get('root_path').'public'.DS.'upload'.DS.'normal'.DS.'租户Excel模板.xls';

     if (! file_exists($file_dir) ) {
            $this->error('文件未找到');
        }else{
            // 打开文件
            $file1 = fopen($file_dir, "r");
            // 输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length:".filesize($file_dir));
            Header("Content-Disposition: attachment;filename=租户Excel模板.xls");
            ob_clean();     // 重点！！！
            flush();        // 重点！！！！可以清除文件中多余的路径名以及解决乱码的问题：
            //输出文件内容
            //读取文件内容并直接输出到浏览器
            echo fread($file1, filesize($file_dir));
            fclose($file1);
            exit();
        }

    }

}
